package com.studysystem.controller;

import com.studysystem.dto.CourseReviewRequest;
import com.studysystem.entity.Course;
import com.studysystem.entity.CourseReview;
import com.studysystem.entity.User;
import com.studysystem.repository.CourseRepository;
import com.studysystem.repository.CourseReviewRepository;
import com.studysystem.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/review")
public class CourseReviewController {
    @Autowired
    private CourseReviewRepository reviewRepository;
    @Autowired
    private CourseRepository courseRepository;
    @Autowired
    private UserRepository userRepository;

    // 提交评价
    @PostMapping
    public Map<String, Object> submitReview(@AuthenticationPrincipal UserDetails userDetails, @RequestBody CourseReviewRequest request) {
        Map<String, Object> res = new HashMap<>();
        Optional<User> userOpt = userRepository.findByUsername(userDetails.getUsername());
        if (userOpt.isEmpty()) { res.put("success", false); res.put("message", "用户不存在"); return res; }
        User user = userOpt.get();
        Course course = courseRepository.findById(request.getCourseId()).orElse(null);
        if (course == null) { res.put("success", false); res.put("message", "课程不存在"); return res; }
        CourseReview review = reviewRepository.findByUserIdAndCourseId(user.getId(), request.getCourseId()).orElse(new CourseReview());
        review.setUser(user);
        review.setCourse(course);
        review.setRating(request.getRating());
        review.setComment(request.getComment());
        review.setCreatedAt(LocalDateTime.now());
        review.setUpdatedAt(LocalDateTime.now());
        reviewRepository.save(review);
        res.put("success", true);
        return res;
    }

    // 评价列表（分页+排序+统计）
    @GetMapping("/list")
    public Map<String, Object> getReviewList(@RequestParam Long courseId, @RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size, @RequestParam(defaultValue = "hot") String sort, @AuthenticationPrincipal UserDetails userDetails) {
        Map<String, Object> res = new HashMap<>();
        Sort s = sort.equals("new") ? Sort.by(Sort.Direction.DESC, "createdAt") : Sort.by(Sort.Direction.DESC, "rating", "createdAt");
        Page<CourseReview> reviewPage = reviewRepository.findByCourseId(courseId, PageRequest.of(page-1, size, s));
        List<Map<String, Object>> reviews = reviewPage.getContent().stream().map(r -> {
            Map<String, Object> m = new HashMap<>();
            m.put("id", r.getId());
            m.put("userName", r.getUser() != null ? (r.getUser().getFullName() != null ? r.getUser().getFullName() : r.getUser().getUsername()) : "");
            m.put("anonymous", false); // 可根据需求调整
            m.put("score", r.getRating());
            m.put("content", r.getComment());
            m.put("createdAt", r.getCreatedAt());
            m.put("likes", 0); // 需实现点赞功能
            m.put("liked", false); // 需实现点赞功能
            m.put("isMine", userDetails != null && r.getUser() != null && r.getUser().getUsername().equals(userDetails.getUsername()));
            return m;
        }).collect(Collectors.toList());
        // 统计
        List<CourseReview> all = reviewRepository.findByCourseId(courseId);
        double avgScore = all.stream().mapToInt(CourseReview::getRating).average().orElse(0);
        Map<Integer, Long> starStats = all.stream().collect(Collectors.groupingBy(CourseReview::getRating, Collectors.counting()));
        Map<Integer, Long> starMap = new HashMap<>();
        for(int i=1;i<=5;i++) starMap.put(i, starStats.getOrDefault(i,0L));
        res.put("total", all.size());
        res.put("avgScore", avgScore);
        res.put("starStats", starMap);
        res.put("reviews", reviews);
        return res;
    }

    // 删除评价
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteReview(@PathVariable Long id, @AuthenticationPrincipal UserDetails userDetails) {
        Map<String, Object> res = new HashMap<>();
        Optional<CourseReview> reviewOpt = reviewRepository.findById(id);
        if (reviewOpt.isEmpty()) { res.put("success", false); res.put("message", "评价不存在"); return res; }
        CourseReview review = reviewOpt.get();
        if (userDetails == null || !review.getUser().getUsername().equals(userDetails.getUsername())) {
            res.put("success", false); res.put("message", "无权删除"); return res;
        }
        reviewRepository.deleteById(id);
        res.put("success", true);
        return res;
    }

    // 点赞功能（示例，实际需新建表记录用户点赞）
    @PostMapping("/like")
    public Map<String, Object> likeReview(@RequestBody Map<String, Long> req) {
        Map<String, Object> res = new HashMap<>();
        // TODO: 实现点赞计数和去重
        res.put("success", true);
        return res;
    }
} 